//
//  RHHouseDetailsVC.swift
//  IMF
//
//  Created by 黄瑞东 on 2018/9/17.
//  Copyright © 2018年 imf. All rights reserved.
//

import UIKit
import Mapbox
import TPPDF
import SVProgressHUD

class RHHouseDetailsVC: RHViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDelegate, UITableViewDataSource, MGLMapViewDelegate {
    
    var collectionView: UICollectionView?
    let width = UIScreen.main.bounds.size.width//获取屏幕宽
    let height = UIScreen.main.bounds.size.height//获取屏幕高
    var tableView: RHTableView?
    var footerView: UIView?
    var headerView: UIView?
    var houseId = String()
    var photosModel = RHHousePhotosModel()
    var imageArray: Array<UIImage>?
    var tableModel = RHHousingDetailsShowModel()
    var mapView:MGLMapView?
    var chartsViewHeight = 0
    var pieChartView = RHPieChartView()
    var barChartView = RHBarChartView()
    var lineChartView = RHlineChartView()
    var housingSurroundingAgeModel:RHHousingSurroundingAgeModel?
    var housingSurroundingCostsModel:RHHousingSurroundingCostsModel?
    var housingSurroundingCrimeModel:RHHousingSurroundingCrimeModel?
    var housingSurroundingEducationModel:RHHousingSurroundingEducationModel?
    var housingSurroundingEmploymentModel: RHHousingSurroundingEmploymentModel?
    var housingSurroundingGenderModel: RHHousingSurroundingGenderModel?
    var housingSurroundingHouseholdModel: RHHousingSurroundingHouseholdModel?
    var housingSurroundingIncomeModel: RHHousingSurroundingIncomeModel?
    var housingSurroundingPopulationModel:RHHousingSurroundingPopulationModel?
    var housingSurroundingWeatherModel:RHHousingSurroundingWeatherModel?
    var crimeModel = RHCrimeModel()
    var ageModel = RHAgeDModel()
    var costsModel = RHCostsModel()
    var educationModel = RHEducationModel()
    var employmentModel = RHEmploymentModel()
    var genderModel = RHGenderModel()
    var householdModel = RHHouseholdModel()
    var incomeModel = RHIncomeModel()
    var populationModel = RHPopulationModel()
    var weatherModel = RHWeatherModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = NSLocalizedString("HouseDetailsTitle", comment: "")
        imageArray = Array()
        loadTableView()
        loadHousePhotosApi()
        loadHouseDetailsApi()
        loadCheckHousingSurroundingAgeApi()
        loadCheckHousingSurroundingCostsApi()
        loadCheckHousingSurroundingCrimeApi()
        loadCheckHousingSurroundingEducationApi()
        loadCheckHousingSurroundingEmploymentApi()
        loadCheckHousingSurroundingGenderApi()
        loadCheckHousingSurroundingHouseholdApi()
        loadCheckHousingSurroundingIncomeApi()
        loadCheckHousingSurroundingPopulationApi()
        loadCheckHousingSurroundingWeatherApi()
    }

    func loadCheckHousingSurroundingWeatherApi() {
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doCheckHousingSurroundingWeather(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.housingSurroundingWeatherModel = (data as! RHHousingSurroundingWeatherModel)
            weakSelf.weatherModel.allocData(data: weakSelf.housingSurroundingWeatherModel!)
            weakSelf.tableView?.tableFooterView = weakSelf.loadFooterView()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    func loadCheckHousingSurroundingPopulationApi() {
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doCheckHousingSurroundingPopulation(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.housingSurroundingPopulationModel = (data as! RHHousingSurroundingPopulationModel)
            weakSelf.populationModel.allocData(data: weakSelf.housingSurroundingPopulationModel!)
            weakSelf.tableView?.tableFooterView = weakSelf.loadFooterView()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadCheckHousingSurroundingIncomeApi() {
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doCheckHousingSurroundingIncome(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.housingSurroundingIncomeModel = (data as! RHHousingSurroundingIncomeModel)
            weakSelf.incomeModel.allocData(data: weakSelf.housingSurroundingIncomeModel!)
            weakSelf.tableView?.tableFooterView = weakSelf.loadFooterView()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadCheckHousingSurroundingHouseholdApi() {
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doCheckHousingSurroundingHousehold(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.housingSurroundingHouseholdModel = (data as! RHHousingSurroundingHouseholdModel)
            weakSelf.householdModel.allocData(data: weakSelf.housingSurroundingHouseholdModel!)
            weakSelf.tableView?.tableFooterView = weakSelf.loadFooterView()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadCheckHousingSurroundingGenderApi() {
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doCheckHousingSurroundingGender(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.housingSurroundingGenderModel = (data as! RHHousingSurroundingGenderModel)
            weakSelf.genderModel.allocData(data: weakSelf.housingSurroundingGenderModel!)
            weakSelf.tableView?.tableFooterView = weakSelf.loadFooterView()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadCheckHousingSurroundingEmploymentApi() {
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doCheckHousingSurroundingEmployment(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.housingSurroundingEmploymentModel = (data as! RHHousingSurroundingEmploymentModel)
            weakSelf.employmentModel.allocData(data: weakSelf.housingSurroundingEmploymentModel!)
            weakSelf.tableView?.tableFooterView = weakSelf.loadFooterView()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadCheckHousingSurroundingEducationApi() {
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doCheckHousingSurroundingEducation(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.housingSurroundingEducationModel = (data as! RHHousingSurroundingEducationModel)
            weakSelf.educationModel.allocData(data: weakSelf.housingSurroundingEducationModel!)
            weakSelf.tableView?.tableFooterView = weakSelf.loadFooterView()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadCheckHousingSurroundingCrimeApi(){
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doCheckHousingSurroundingCrime(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.housingSurroundingCrimeModel = (data as! RHHousingSurroundingCrimeModel)
            weakSelf.crimeModel.allocData(data: weakSelf.housingSurroundingCrimeModel!)
            weakSelf.tableView?.tableFooterView = weakSelf.loadFooterView()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadCheckHousingSurroundingCostsApi(){
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doCheckHousingSurroundingCosts(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.housingSurroundingCostsModel = (data as! RHHousingSurroundingCostsModel)
            weakSelf.costsModel.allocData(data: weakSelf.housingSurroundingCostsModel!)
            weakSelf.tableView?.tableFooterView = weakSelf.loadFooterView()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadCheckHousingSurroundingAgeApi(){
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doCheckHousingSurroundingAge(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.housingSurroundingAgeModel = (data as! RHHousingSurroundingAgeModel)
            weakSelf.ageModel.allocData(data: weakSelf.housingSurroundingAgeModel!)
            weakSelf.tableView?.tableFooterView = weakSelf.loadFooterView()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadHouseDetailsApi(){
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doHomesDetail(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            weakSelf.tableModel.RHGetDetailsData(model: data as! RHHousingDetailsModel)
            weakSelf.tableView?.tableFooterView = weakSelf.loadFooterView()
            weakSelf.tableView?.delegate = self;
            weakSelf.tableView?.dataSource = self;
            weakSelf.tableView?.reloadData()
            SVProgressHUD.dismiss()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadAnnotations() {
        var cLLocationCoordinate2D:CLLocationCoordinate2D?
        let array = NSMutableArray()
        let pointAnnotation = MGLPointAnnotation()
        cLLocationCoordinate2D = CLLocationCoordinate2DMake(CLLocationDegrees(self.tableModel.lat), CLLocationDegrees(self.tableModel.lng))
        pointAnnotation.coordinate = cLLocationCoordinate2D!
        array.add(pointAnnotation)
        self.mapView?.isScrollEnabled = false
        self.mapView?.isRotateEnabled = false
        self.mapView?.isPitchEnabled = false
        self.mapView?.isZoomEnabled = false
        self.mapView?.addAnnotations(array as! [MGLAnnotation])
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(mapClick))
        tapGesture.numberOfTapsRequired = 1
        self.mapView?.addGestureRecognizer(tapGesture)
    }
    
    func loadHousePhotosApi(){
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doHousePhotos(houseId: houseId, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.photosModel = data as! RHHousePhotosModel
            weakSelf.tableView?.reloadData()
            weakSelf.collectionView?.reloadData()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadTableView() {
        self.tableView = RHTableView(frame: CGRect.zero, style: .plain)
        self.tableView?.register(RHKeyValueTableViewCell.self, forCellReuseIdentifier: "RHKeyValueTableViewCell")
        self.tableView?.register(RHCollectionViewTableViewCell.self, forCellReuseIdentifier: "RHCollectionViewTableViewCell")
        self.tableView?.register(RHContentTableViewCell.self, forCellReuseIdentifier: "RHContentTableViewCell")
        self.view.addSubview(self.tableView!)
        self.tableView?.snp.makeConstraints { [weak self](make) in
            guard let weakSelf = self else { return }
            make.top.equalTo(10)
            make.left.equalTo(weakSelf.view.snp.left)
            make.right.equalTo(weakSelf.view.snp.right)
            make.bottom.equalTo(weakSelf.view.snp.bottom)
        }
    }
    
    func loadHeaderView() -> UIView{
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width:(width - 60) / 3, height:(width - 60) / 3)
        layout.headerReferenceSize = CGSize.init(width: width - 30, height: 0)
        self.headerView = UIView(frame: CGRect(x: 0, y: 0, width: width, height:self.photosModel.data == nil ? 0 : (self.photosModel.data?.count)! >= 9 ? width - 20 : (self.photosModel.data?.count)! > 6 ? width - 20 : (self.photosModel.data?.count)! > 4 ? (width - 20) / 3 * 2 : (width - 20) / 3))
        self.collectionView  = UICollectionView(frame: CGRect(x: 15, y: 0, width: width - 30, height: (self.headerView?.frame.height)!), collectionViewLayout: layout)
        self.collectionView! .register(RHImageViewCollectionViewCell.self, forCellWithReuseIdentifier:"cell")
        self.collectionView! .register(RHCityCollectionReusableView.self, forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier)
        self.collectionView?.backgroundColor = RHAppSkinColor.sharedInstance.viewBackgroundColor
        self.collectionView?.dataSource = self
        self.collectionView?.delegate = self
        self.headerView?.addSubview(self.collectionView!)
        return self.headerView!
    }
    
    func createPDF() -> URL{
        let document = PDFDocument(format: .a4)
        document.addImage(image: PDFImage(image: scrollViewScreenShot(self.tableView!, frame: nil)!))
        var url: URL
        do {
            url = try PDFGenerator.generateURL(document: document, filename: RHAppConfig.sharedInstance.appName, progress: { progress in
                print(progress)
            }, debug: false)
        } catch {
            url = URL(string: "error")!
        }
        return url
    }
    
    @objc func mapClick() {
        let vc = RHMapDetailsVC()
        vc.houseId = self.houseId
        vc.lat = self.tableModel.lat
        vc.lng = self.tableModel.lng
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    private func scrollViewScreenShot(_ scrollView: UIScrollView, frame: CGRect?) -> UIImage? {
        scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height)

        let shotFrame: CGRect = (frame == nil) ? CGRect(origin: CGPoint(), size: scrollView.contentSize) : frame!
        UIGraphicsBeginImageContextWithOptions(shotFrame.size, false, 0)
        let savedContentOffset = scrollView.contentOffset
        let savedFrame = scrollView.frame
        scrollView.contentOffset = CGPoint()
        scrollView.frame = CGRect(origin: CGPoint(), size: scrollView.contentSize)
        guard let currentContext = UIGraphicsGetCurrentContext() else { return nil }
        currentContext.translateBy(x: -shotFrame.origin.x, y: -shotFrame.origin.y)
        let path = UIBezierPath(rect: shotFrame)
        path.addClip()
        scrollView.layer.render(in: currentContext)
        var image = UIGraphicsGetImageFromCurrentImageContext()
        if image == nil {
            image = UIImage()
        }
        UIGraphicsEndImageContext()
        scrollView.contentOffset = savedContentOffset
        scrollView.frame = savedFrame
        return image
    }

    @objc func addShareButtonClick() {
        let vc = RHShareGroupListVC()
        vc.houseId = self.houseId

        self.present(RHCustomNavigationController(rootViewController: vc), animated: true, completion: nil)
    }
    
    @objc func recommendedButtonClick() {
        let vc = RHBuyersListViewController()
        vc.houseId = self.houseId
        self.present(RHCustomNavigationController(rootViewController: vc), animated: true, completion: nil)
    }
    
    @objc func shareClick() {
        let message =  WXMediaMessage()
        let _scene = Int32(WXSceneSession.rawValue)
        let image =  scrollViewScreenShot(self.tableView!, frame: nil)!
        let imageObject =  WXImageObject()
        imageObject.imageData = UIImageJPEGRepresentation(image, 0.1)
        message.mediaObject = imageObject
        let req =  SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = _scene
        WXApi.send(req)
        
//        let image = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
//        image.image = snapshot
//
//        self.view.addSubview(image)
//        let message =  WXMediaMessage()
//        message.title = RHAppConfig.sharedInstance.wShareTitle
//        message.description = RHAppConfig.sharedInstance.wShareDescription
////        let ext =  WXFileObject()
////        ext.fileExtension = RHAppConfig.sharedInstance.PDFExtension
////        let url = createPDF()
////        if url == URL(string: "error") {
////            SVProgressHUD.showInfo(withStatus: NSLocalizedString("CreatePDFError", comment: ""))
////        }else{
////            ext.fileData = try! Data(contentsOf: url)
////            message.mediaObject = ext
//            let req =  SendMessageToWXReq()
//            req.bText = false
//            req.message = message
//            req.scene = _scene
//            WXApi.send(req)
//        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.photosModel.data == nil ? 0 : (self.photosModel.data?.count)! > 9 ? 9 : (self.photosModel.data?.count)!
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = RHHouseImagelistVC()
        vc.imageDataArray = self.photosModel.data
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! RHImageViewCollectionViewCell
        cell.imageView?.image = UIImage(named: "placeholder")

        if self.photosModel.data != nil{
            if (imageArray?.count)! <= indexPath.row {
                let url = URL(string: self.photosModel.data![indexPath.row])
                let request =  URLRequest(url: url!)
                let session  = URLSession.shared
                let dataTask =  session.dataTask(with: request, completionHandler: {
                    (data, response, taskError) -> Void in
                    if taskError != nil{
                        print(taskError.debugDescription)
                    }else{
                        DispatchQueue.main.async {
                            self.imageArray!.append(UIImage(data: data!)!)
                            cell.imageView?.image = UIImage(data: data!)
                        }
                    }
                }) as URLSessionTask
                dataTask.resume()
            }else{
                cell.imageView?.image = imageArray![indexPath.row]
            }
        }else{
            self.imageArray?.append(UIImage(named: "placeholder")!)
        }
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return tableModel.rowsCount.count + 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section > tableModel.rowsCount.count + 1{
            return 0
        }
        
        if section == 0 {
            return 1
        }else{
            return tableModel.rowsCount[section - 1] as! Int
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell: RHCollectionViewTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RHCollectionViewTableViewCell", for: indexPath) as! RHCollectionViewTableViewCell
            cell.collectionView?.delegate = self
            cell.collectionView?.dataSource = self
            cell.collectionView?.frame = CGRect(x: 15, y: 0, width: width - 30, height:self.photosModel.data == nil ? 0 : (self.photosModel.data?.count)! >= 9 ? width - 20 : (self.photosModel.data?.count)! > 6 ? width - 20 : (self.photosModel.data?.count)! > 4 ? (width - 20) / 3 * 2 : (width - 20) / 3)
            cell.backgroundColor = RHAppSkinColor.sharedInstance.viewBackgroundColor
            return cell
        }else if indexPath.section == tableModel.rowsCount.count {
            let contentTableViewCell: RHContentTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RHContentTableViewCell", for: indexPath) as! RHContentTableViewCell
            let rows = indexPath.section - (tableModel.rightDataArray[1] as! NSArray).count - 2
            contentTableViewCell.leftLabel?.text = ((tableModel.rightDataArray[2] as! NSArray)[rows] as! NSArray)[indexPath.row] as? String
            contentTableViewCell.leftLabel?.frame = CGRect(x: 20, y: 2, width: Int(width - 40), height: (contentTableViewCell.leftLabel?.text?.count)! / 50 * 20)
            return contentTableViewCell
        }else {
            let cell: RHKeyValueTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RHKeyValueTableViewCell", for: indexPath) as! RHKeyValueTableViewCell
            if indexPath.section == 1 {
                cell.leftLabel?.text = (tableModel.leftDataArray[0] as! NSArray)[indexPath.row] as? String
                cell.rightLabel?.text = (tableModel.rightDataArray[0] as! NSArray)[indexPath.row] as? String
            }else if indexPath.section <= (tableModel.rightDataArray[1] as! NSArray).count + 1{
                cell.leftLabel?.text =  ((tableModel.rightDataArray[1] as! NSArray)[indexPath.section - 2] as! NSArray)[indexPath.row] as? String
                cell.rightLabel?.text = ""
            }else if indexPath.section <= (tableModel.rightDataArray[1] as! NSArray).count + (tableModel.rightDataArray[2] as! NSArray).count + 1{
                let rows = indexPath.section - (tableModel.rightDataArray[1] as! NSArray).count - 2
                cell.leftLabel?.text = ((tableModel.leftDataArray[2] as! NSArray)[rows] as! NSArray)[indexPath.row + 1] as? String
                cell.rightLabel?.text = ((tableModel.rightDataArray[2] as! NSArray)[rows] as! NSArray)[indexPath.row] as? String
            }else{
                cell.leftLabel?.text = ""
                cell.rightLabel?.text = ""
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
        }else {
            let view = UIView()
            view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 40)
            view.backgroundColor = RHAppSkinColor.sharedInstance.viewBackgroundColor
            var label = UILabel()
            label = UILabel.xz_labelWithFontSize(size: 14.0, textColor: RHAppSkinColor.sharedInstance.secondaryTextColor, backgroundColor: nil, numberOfLines: 1)
            view.addSubview(label)
            label.snp.makeConstraints({(make) in
                make.top.equalTo(2.0)
                make.left.equalTo(20.0)
                make.width.equalTo(120.0)
                make.height.equalTo(40)
            })
            if section == 1 {
                label.text = "房源详情"
            } else if section <= (tableModel.rightDataArray[1] as! NSArray).count + 1{
                label.text = (tableModel.leftDataArray[1] as! NSArray)[section - 2] as? String
            }else if section <= (tableModel.rightDataArray[1] as! NSArray).count + (tableModel.rightDataArray[2] as! NSArray).count + 1{
                label.text = ((tableModel.leftDataArray[2] as! NSArray)[section - 2 - (tableModel.rightDataArray[1] as! NSArray).count] as! NSArray)[0] as? String
            }
            return view
        }
        return nil
    }
    
    func loadCircularChart(description:String,data:NSArray) -> UIView {
         let colorArray = [UIColor.red,UIColor.blue,UIColor.purple,UIColor.green,UIColor.black,UIColor.yellow,UIColor.orange,UIColor.magenta,UIColor.red,UIColor.blue,UIColor.purple,UIColor.green,UIColor.black,UIColor.yellow,UIColor.orange,UIColor.magenta,UIColor.red,UIColor.blue,UIColor.purple,UIColor.green]
        let view = UIView()
        let arrayData = NSMutableArray()

        for i in 0...data.count - 1{
             arrayData.add(["title":(data[i] as! NSDictionary)["text"],"data":(data[i] as! NSDictionary)["data"],"color":colorArray[i]])
        }
        let chartView = UIView(frame: CGRect(x: 0, y: CGFloat(chartsViewHeight), width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width))
        pieChartView.RH_CreatePieChartView(view: chartView, description: description, data: arrayData)
        view.addSubview(chartView)
        chartsViewHeight = chartsViewHeight + Int(width)
        return view
    }
    
    func loadBarChartView(description:String,data:NSArray) -> UIView {
        let colorArray = [UIColor.red,UIColor.blue,UIColor.purple,UIColor.green,UIColor.black,UIColor.yellow,UIColor.orange,UIColor.magenta,UIColor.red,UIColor.blue,UIColor.purple,UIColor.green]
        let view = UIView()
        let arrayData = NSMutableArray()
        
        for i in 0...data.count - 1{
            arrayData.add(["title":(data[i] as! NSDictionary)["text"],"data":(data[i] as! NSDictionary)["data"],"color":colorArray[i]])
        }
        let chartView = UIView(frame: CGRect(x: 0, y: CGFloat(chartsViewHeight), width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width))
        barChartView.RH_CreatebarChartView(view: chartView, description: description, data: arrayData)
        view.addSubview(chartView)
        chartsViewHeight = chartsViewHeight + Int(width)
        return view
    }
    
    func loadLineChartView(description:String,data:NSArray,titleArray:NSArray,xValues:NSArray) -> UIView {
        let colorArray = [UIColor.red,UIColor.blue,UIColor.purple,UIColor.green,UIColor.black,UIColor.yellow,UIColor.orange,UIColor.magenta,UIColor.red,UIColor.blue,UIColor.purple,UIColor.green]
        let view = UIView()
        let arrayData = NSMutableArray()

        for i in 0...data.count - 1{
            let array = NSMutableArray()
            for j in 0...(data[i] as! NSArray).count - 1{
                array.add((data[i] as! NSArray)[j] as! Float)
            }
            arrayData.add(["data":array,"color":colorArray[i],"title":titleArray[i]])
        }
        let chartView = UIView(frame: CGRect(x: 0, y: CGFloat(chartsViewHeight), width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width))
        lineChartView.RH_CreatelineChartView(view: chartView, description: description, data: arrayData, xValues: xValues)
        view.addSubview(chartView)
        chartsViewHeight = chartsViewHeight + Int(width)
        return view
    }
    
    func loadFooterView() -> UIView{
        self.footerView = UIView()
        chartsViewHeight = 0
        if self.ageModel.ageDataArray != nil{
            self.footerView?.addSubview(loadCircularChart(description: "人口年龄比例", data: self.ageModel.ageDataArray!))
        }
        if self.ageModel.raceArray != nil{
            self.footerView?.addSubview(loadCircularChart(description: "种族比例", data: self.ageModel.raceArray!))
        }
        if self.costsModel.dataArray != nil{
            self.footerView?.addSubview(loadBarChartView(description: "生活成本指数", data: self.costsModel.dataArray!))
        }
        if self.crimeModel.dataArray != nil{
            self.footerView?.addSubview(loadBarChartView(description: "犯罪指数", data: self.crimeModel.dataArray!))
        }
        if self.educationModel.dataArray != nil{
            self.footerView?.addSubview(loadCircularChart(description: "教育比例", data: self.educationModel.dataArray!))
        }
        if self.employmentModel.dataArray != nil{
            self.footerView?.addSubview(loadCircularChart(description: "就业比例", data: self.employmentModel.dataArray!))
        }
        if self.genderModel.dataArray != nil{
            self.footerView?.addSubview(loadCircularChart(description: "男女比例", data: self.genderModel.dataArray!))
        }
        if self.householdModel.dataArray != nil{
            self.footerView?.addSubview(loadBarChartView(description: "同屋居住者统计", data: self.householdModel.dataArray!))
        }
        if self.incomeModel.dataArray != nil{
            self.footerView?.addSubview(loadCircularChart(description: "收入统计", data: self.incomeModel.dataArray!))
        }
        if self.populationModel.dataArray != nil{
            self.footerView?.addSubview(loadBarChartView(description: "人口统计", data: self.populationModel.dataArray!))
        }
        if self.weatherModel.dataArray != nil{
            self.footerView?.addSubview(loadLineChartView(description: "温度统计", data: self.weatherModel.dataArray!, titleArray: self.weatherModel.dataTitleArray!, xValues: ["最低温度","最高温度"]))
        }
        if self.weatherModel.indicesArray != nil{
            self.footerView?.addSubview(loadBarChartView(description: "灾害指数", data: self.weatherModel.indicesArray!))
        }
        
        let viewY =  (self.tableModel.lat > 0 ? width / 2 : 0) + CGFloat(chartsViewHeight)

        let shareButton = UIButton.xz_commonButtonWithTitle(title: NSLocalizedString("shareText", comment: ""), isEnabled: true)
        shareButton.frame = CGRect(x: 15, y: 40 + viewY, width: width - 40, height: 44)
        shareButton.addTarget(self, action: #selector(shareClick), for: .touchUpInside)
        self.footerView?.addSubview(shareButton)
        
        let recommendedButton = UIButton.xz_commonButtonWithTitle(title: "推荐房源", isEnabled: true)
        recommendedButton.frame = CGRect(x: 15, y: 100 + viewY, width: width - 40, height: 44)
        recommendedButton.addTarget(self, action: #selector(recommendedButtonClick), for: .touchUpInside)
        self.footerView?.addSubview(recommendedButton)
        
        let addShareButton = UIButton.xz_commonButtonWithTitle(title: "添加到分享组", isEnabled: true)
        addShareButton.frame = CGRect(x: 15, y: 160 + viewY, width: width - 40, height: 44)
        addShareButton.addTarget(self, action: #selector(addShareButtonClick), for: .touchUpInside)
        self.footerView?.addSubview(addShareButton)
        
        footerView?.frame = CGRect(x: 0, y: 0, width: width, height: addShareButton.frame.origin.y + addShareButton.frame.height + 20)
        
        if self.tableModel.lat > 0{
            mapView = MGLMapView(frame: CGRect(x: 0, y: CGFloat(chartsViewHeight + 10), width: width, height: width / 2), styleURL: URL(string: RHAppConfig.sharedInstance.mapboxURL))
            mapView!.setCenter(CLLocationCoordinate2D(latitude: CLLocationDegrees(tableModel.lat), longitude: CLLocationDegrees(tableModel.lng)), zoomLevel: 12, animated: false)
            loadAnnotations()
            self.footerView?.addSubview(mapView!)
        }

        return footerView!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return self.photosModel.data == nil ? 0 : (self.photosModel.data?.count)! >= 9 ? width - 20 : (self.photosModel.data?.count)! > 6 ? width - 20 : (self.photosModel.data?.count)! > 4 ? (width - 20) / 3 * 2 : (width - 20) / 3
        }else if indexPath.section == self.tableModel.rowsCount.count{
            let rows = indexPath.section - (tableModel.rightDataArray[1] as! NSArray).count - 2
            return CGFloat(((((tableModel.rightDataArray[2] as! NSArray)[rows] as! NSArray)[indexPath.row] as? String)?.count)! / 50 * 20)
        }
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0
        }else{
            return 40
        }
    }
}
